package com.example.myblog1_0.controller;

import com.example.myblog1_0.model.Article;
import com.example.myblog1_0.model.MyUser;
import com.example.myblog1_0.service.ArticleService;
import com.example.myblog1_0.service.UserService;
import com.example.myblog1_0.service.WebMsgService;
import com.example.myblog1_0.util.IPUtil;
import com.zhenzi.sms.ZhenziSmsClient;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Random;

/**
 * @Author: xc
 * @Date: 2018/12/14 16:46
 * @Description:
 **/
@RestController
public class IndexController {
    @Autowired
    UserService userService;
    @Autowired
    ArticleService articleService;
    @Autowired
    WebMsgService webMsgService;

    @PostMapping("/sendMeg")
    public JSONObject sendMeg(@RequestParam("number") String number){
        JSONObject jsonObject = new JSONObject();
         String apiUrl = "https://sms_developer.zhenzikj.com";
         String appId = "榛子云账户";
         String appSecret = "榛子云账户";
         String verifyCode = String.valueOf(new Random().nextInt(899999) + 100000);
         try {
             ZhenziSmsClient client = new ZhenziSmsClient(apiUrl,appId,appSecret);
             String result = client.send(number,"您的验证码为:" + verifyCode + "，该码有效期为5分钟，该码只能使用一次!");
             System.out.println(result);
             jsonObject.put("status",200);
             jsonObject.put("verifyCode",verifyCode);
             jsonObject.put("createTime", System.currentTimeMillis());
             return jsonObject;
         } catch (Exception e) {
             e.printStackTrace();
             jsonObject.put("status",403);
             jsonObject.put("message","发送验证码失败");
             return jsonObject;
         }
    }
    @PostMapping("/doRegister")
    public JSONObject doRegister(MyUser myUser,
                                 @RequestParam("code") String code,
                                 @RequestParam("verifyCode") String verifyCode){
        JSONObject returnObject = new JSONObject();
        myUser.setRole("ROLE_USER");
        if (code.equals(verifyCode)) {
            BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
            String password = bCryptPasswordEncoder.encode(myUser.getPassword());
            myUser.setPassword(password);

            myUser.setAvatarUrl("https://xzio.oss-cn-beijing.aliyuncs.com/static/img/defult.jpg");
            MyUser findUser = userService.findUserInfoByName(myUser.getUsername());
            if (findUser == null) {
                boolean flag = userService.insetUser(myUser);
                if (flag) {
                    returnObject.put("status", 1);
                    returnObject.put("message", "注册成功");
                } else {
                    returnObject.put("status", 0);
                    returnObject.put("message", "注册失败");
                }
            } else {
                returnObject.put("status", 2);
                returnObject.put("message", "用户名已存在");
            }
            return returnObject;
        }else {
            returnObject.put("status",3);
            returnObject.put("message","验证码错误");
            return returnObject;
        }
    }
    @GetMapping("/checkNickname")
    public JSONObject checkNickname(@RequestParam("nickname")String nickname){
        return userService.findUserByNickname(nickname);
    }

    @GetMapping("/getArticle")
    public JSONObject getArticle(Article article){
        JSONObject returnObject = new JSONObject();
        Article find = articleService.findArticleByTitle(article.getTitle());
        if (find == null){
            returnObject.put("status",0);
            returnObject.put("message","未找到");
            return  returnObject;
        }else{
            returnObject.put("status",1);
            returnObject.put("message","找到");
            returnObject.put("id",find.getId());
            returnObject.put("title",find.getTitle());
            returnObject.put("summary",find.getSummary());
            returnObject.put("articleContent",find.getArticleContent());
            returnObject.put("writeTime",find.getWriteTime());
            returnObject.put("articleCategories",find.getArticleCategories());
            return returnObject;
        }
    }

    /**
     * 获得最近更新的3篇文章
     * @return
     */
    @GetMapping("/getNewArticle")
    public JSONObject getNewArticle(){
        List<Article> articles = articleService.findAllArticleDesc();
        JSONArray group = new JSONArray();
       // SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        JSONObject jsonObject;
        for (int i = 0; i < 3; i++) {
            String time = articles.get(i).getWriteTime();
            jsonObject = new JSONObject();
            jsonObject.put("id",articles.get(i).getId());
            jsonObject.put("title",articles.get(i).getTitle());
            jsonObject.put("summary",articles.get(i).getSummary());
            jsonObject.put("articleContent",articles.get(i).getArticleContent());
            jsonObject.put("articleCategories",articles.get(i).getArticleCategories());
            jsonObject.put("writeTime",time);
            group.add(jsonObject);
        }
        JSONObject returnObject = new JSONObject();
        if (articles.size() != 0){
            returnObject.put("status",1);
            returnObject.put("message","获取成功");
            returnObject.put("result",group);
            return returnObject;
        }else {
            returnObject.put("status",0);
            returnObject.put("message","获取失败");
            return returnObject;
        }
    }
    @GetMapping("/getAllArticleDesc")
    public JSONObject getAllArticleDesc(@RequestParam("row") String row,@RequestParam("pageNum") String pageNum){
        return articleService.getAllArticleDesc(Integer.parseInt(row),Integer.parseInt(pageNum));
    }
    @PostMapping("/getWebMsg")
    public JSONObject getWebMsg(HttpServletRequest request){
        String ip = IPUtil.getClientIp(request);
        webMsgService.updateNum();
        if (webMsgService.queryIP(ip)==null){
            webMsgService.insertIP(ip);
        }

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("visitorCount",webMsgService.getVisitorNum());
        jsonObject.put("IPCount",webMsgService.getIPNum());
        return jsonObject;
    }
}



